<template>
  <div class="member-container">
    <!-- 搜索卡片 -->
    <div class="search-card">
      <el-input
          v-model="data.memberNo"
          placeholder="请输入党/团员编号查询"
          class="search-input"
          :prefix-icon="Search"
      />
      <el-button type="danger" plain @click="load()">查询</el-button>
      <el-button type="danger" plain @click="reset">重置</el-button>
    </div>

    <!-- 数据表格卡片 -->
    <div class="data-card">
      <div class="button-group" v-if="data.currentUser.userType !== 5">
        <el-button type="danger" @click="handleAdd">
          <el-icon><Plus /></el-icon> 新增成员
        </el-button>
        <el-button type="danger" plain @click="delBatch">
          <el-icon><Delete /></el-icon> 批量删除
        </el-button>
      </div>

      <el-table :data="data.tableData"  max-height="410" stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="45" align="center" v-if="data.currentUser.userType !== 5"/>
        <el-table-column prop="memberNo" label="党/团员编号" min-width="100"/>
        <el-table-column prop="realName" label="姓名" />
        <el-table-column prop="orgType" label="组织类型" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.orgType === 2 ? 'danger' : 'warning'">
              {{ scope.row.orgType === 2 ? '班级团组织' : '团组织' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="branchName" label="所属支部" width="120"/>
        <el-table-column prop="joinTime" label="入党/团时间" width="160" />
        <el-table-column prop="formalTime" label="转正时间" width="120" />
        <el-table-column prop="recommender" label="介绍人" width="100" />
        <el-table-column label="操作" width="180" align="center" fixed="right" v-if="data.currentUser.userType !== 5">
          <template #default="scope">
            <el-button size="default" type="danger" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="default" type="danger" plain @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="data.pageNum"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="data.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total"
        />
      </div>
    </div>

    <!-- 成员表单对话框 -->
    <el-dialog
        :title="data.form.id ? '编辑成员' : '新增成员'"
        v-model="data.formVisible"
        width="600px"
        destroy-on-close
    >
      <el-form
          :model="data.form"
          :rules="rules"
          ref="memberRef"
          label-width="100px"
      >
        <el-form-item label="组织类型" prop="orgType">
          <el-radio-group v-model="data.form.orgType" :disabled="true">
            <el-radio :label="3">班级团组织</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="选择用户" prop="userId">
          <el-select
              v-model="data.form.userId"
              filterable
              remote
              :remote-method="handleUserSearch"
              :loading="data.userLoading"
              placeholder="请输入姓名搜索"
              @change="handleUserChange"
              clearable
              value-key="id"
          >
            <el-option
                v-for="item in data.userOptions"
                :key="item.id"
                :label="item.realName"
                :value="item.id"
            >
              <div style="display: flex; justify-content: space-between; align-items: center">
                <span>{{ item.realName }}</span>
                <span style="color: #8492a6; font-size: 13px">
                  {{ item.userType === 4 ? '教师' : '学生' }}
                </span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 当选择的是学生时显示学生信息 -->
        <el-form-item label="学生信息" v-if="data.selectedUser?.userType === 5">
          <div class="student-info">
            <p>学号：{{ data.studentInfo?.studentNumber }}</p>
            <p>院系：{{ data.studentInfo?.department }}</p>
            <p>专业：{{ data.studentInfo?.major }}</p>
            <p>班级：{{ data.studentInfo?.className }}</p>
            <p>年级：{{ data.studentInfo?.grade }}</p>
            <p>性别：{{ data.studentInfo?.sex }}</p>
          </div>
        </el-form-item>

        <el-form-item label="所属支部" prop="branchId">
          <el-select
              v-model="data.form.branchId"
              filterable
              placeholder="请选择所属支部"
              clearable
          >
            <el-option
                v-for="item in data.branchOptions"
                :key="item.id"
                :label="item.branchName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="成员编号" prop="memberNo">
          <el-input v-model="data.form.memberNo" placeholder="请输入党/团员编号" />
        </el-form-item>

        <el-form-item label="入党/团时间" prop="joinTime">
          <el-date-picker
              v-model="data.form.joinTime"
              type="datetime"
              placeholder="选择入党/团时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="转正时间" prop="formalTime">
          <el-date-picker
              v-model="data.form.formalTime"
              type="datetime"
              placeholder="选择转正时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="danger" @click="submitForm">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Delete } from '@element-plus/icons-vue'
import { getUserInfo } from "@/utils/auth"

// 定义响应式数据
const data = reactive({
  memberNo: '',
  orgType: '',
  memberStatus: '',
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible: false,
  form: {},
  multipleSelection: [],
  ids: [],
  userOptions: [],
  branchOptions: [],
  userLoading: false,
  selectedUser: null,
  studentInfo: null,
  currentUser: getUserInfo() || {},
  branchName: null,
})

// 表单验证规则
const rules = {
  userId: [{ required: true, message: '请选择用户', trigger: 'change' }],
  branchId: [{ required: true, message: '请选择所属支部', trigger: 'change' }],
  memberNo: [{ required: true, message: '请输入成员编号', trigger: 'blur' }],
  joinTime: [{ required: true, message: '请选择入党/团时间', trigger: 'change' }],
  recommender: [{ required: true, message: '请输入介绍人', trigger: 'blur' }]
}

// 搜索用户
const handleUserSearch = async (query) => {
  if (!query) return
  data.userLoading = true
  try {
    const res = await request.get('/sysUser/search', {
      params: {
        realName: query,
        userTypes: '1,2,4,5'  // 改为逗号分隔的字符串
      }
    })
    if (res.code === '200') {
      data.userOptions = res.data
    }
  } finally {
    data.userLoading = false
  }
}


// 用户选择改变
const handleUserChange = async (userId) => {
  if (!userId) {
    data.selectedUser = null
    data.studentInfo = null
    return
  }
  // 获取用户详情
  const res = await request.get(`/sysUser/${userId}`)
  if (res.code === '200') {
    // 修正数据解构方式
    data.selectedUser = res.data.sysUser
    data.studentInfo = res.data.studentInfo
  }
}

// 加载支部选项
const loadBranchOptions = async () => {
  try {
    const res = await request.get('/organizationBranch/getLeaderBranches', {
      params: {
        leaderId: data.currentUser.id,
        orgType: 3 // 1:党组织 2:团组织
      }
    })
    if (res.code === '200') {
      data.branchOptions = res.data
      // 如果是编辑状态且当前支部不在选项中，说明无权限
      if (data.form.id && data.form.branchId) {
        const hasBranch = data.branchOptions.some(item => item.id === data.form.branchId)
        if (!hasBranch) {
          ElMessage.error('您没有权限编辑该支部的成员信息')
          closeDialog()
        }
      }
    } else {
      ElMessage.error(res.msg || '获取支部列表失败')
    }
  } catch (error) {
    console.error('加载支部选项失败:', error)
    ElMessage.error('加载支部选项失败')
  }
}

// 加载数据
const load = () => {
  if(data.currentUser.userType === 5) {
    request.get('organizationMember/selectById/' + data.currentUser.id).then(res => {
      if (res.code === '200') {
        data.branchId = res.data.branchId
        request.get('/organizationMember/selectAll', {
          params: {
            pageNum: data.pageNum,
            pageSize: data.pageSize,
            memberNo: data.memberNo,
            orgType: 3,
            memberStatus: data.memberStatus,
            leaderId: null,
            studentBranchId: data.branchId
          }
        }).then(res => {
          if (res.code === '200') {
            data.tableData = res.data
            data.total = res.data.total
          } else {
            ElMessage.error(res.msg || '获取数据失败')
          }
        })
      } else {
        ElMessage.error(res.msg || '团组织查询失败');
      }
    })
  }
  else {
    request.get('/organizationMember/selectMember', {
      params: {
        pageNum: data.pageNum,
        pageSize: data.pageSize,
        memberNo: data.memberNo,
        orgType: 3,
        memberStatus: data.memberStatus,
        leaderId: data.currentUser.id
      }
    }).then(res => {
      if (res.code === '200') {
        data.tableData = res.data.list
        data.total = res.data.total
      } else {
        ElMessage.error(res.msg || '获取数据失败')
      }
    })
  }
}

// 新增按钮点击
const handleAdd = () => {
  data.selectedUser = null
  data.studentInfo = null
  data.form = {
    orgType: 3,
    memberStatus: 1,
    joinTime: null,
    formalTime: null,
    memberNo: '',
    recommender: '',
    userId: null,
    branchId: null
  }
  loadBranchOptions()
  data.formVisible = true
}

// 编辑按钮点击
const handleEdit = async (row) => {
  // 创建表单数据的深拷贝
  const formData = JSON.parse(JSON.stringify(row))

  // 格式化日期字段
  if (formData.joinTime) {
    formData.joinTime = formatDateTime(formData.joinTime)
  }
  if (formData.formalTime) {
    formData.formalTime = formatDateTime(formData.formalTime)
  }

  data.form = formData
  await loadBranchOptions()

  // 获取用户详情并添加到选项中
  const res = await request.get(`/sysUser/${row.userId}`)
  if (res.code === '200') {
    data.selectedUser = res.data.sysUser
    data.studentInfo = res.data.studentInfo
    data.userOptions = [res.data.sysUser]
  }

  data.formVisible = true
}

// 添加日期格式化函数
const formatDateTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}


const closeDialog = () => {
  data.formVisible = false
  data.selectedUser = null
  data.studentInfo = null
  data.userOptions = [] // 清空用户选项
  data.form = {} // 清空表单
}

// 表单提交前验证
const validateForm = (form) => {
  // 验证转正时间
  if (form.memberStatus === 2 && !form.formalTime) {
    ElMessage.warning('正式成员必须填写转正时间')
    return false
  }

  // 验证转正时间必须晚于入党/团时间
  if (form.formalTime && form.joinTime) {
    if (new Date(form.formalTime) <= new Date(form.joinTime)) {
      ElMessage.warning('转正时间必须晚于入党/团时间')
      return false
    }
  }

  return true
}

// 保存数据
const save = () => {
  if (!validateForm(data.form)) {
    return
  }

  const url = data.form.id ? '/organizationMember/update' : '/organizationMember/add'
  const method = data.form.id ? 'PUT' : 'POST'

  request({
    url,
    method,
    data: data.form,
    params: {
      leaderId: data.currentUser.id
    }
  }).then(res => {
    if (res.code === '200') {
      ElMessage.success('保存成功')
      data.formVisible = false
      load()
    } else {
      ElMessage.error(res.msg || '保存失败')
    }
  })
}


// 删除单条数据
const del = (id) => {
  ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete('/organizationMember/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  })
}

// 批量删除
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning('请选择要删除的记录')
    return
  }

  ElMessageBox.confirm(`确定要删除选中的 ${data.ids.length} 条记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete('/organizationMember/delete/batch', {
      data: data.ids
    }).then(res => {
      if (res.code === '200') {
        ElMessage.success('批量删除成功')
        load()
      } else {
        ElMessage.error(res.msg || '批量删除失败')
      }
    })
  })
}

// 表格多选
const handleSelectionChange = (selection) => {
  data.multipleSelection = selection
  data.ids = selection.map(item => item.id)
}

// 重置搜索条件
const reset = () => {
  data.memberNo = ''
  data.orgType = ''
  data.memberStatus = ''
  load()
}

// 分页大小改变
const handleSizeChange = (val) => {
  data.pageSize = val
  load()
}

// 当前页改变
const handleCurrentChange = (val) => {
  data.pageNum = val
  load()
}

// 表单引用
const memberRef = ref()

// 提交表单
const submitForm = () => {
  memberRef.value.validate((valid) => {
    if (valid) {
      save()
    } else {
      ElMessage.error('请填写必填项')
      return false
    }
  })
}

// 初始化
onMounted(() => {
  load()
})
</script>

<style scoped>
.member-container {
  padding: 20px;
  width: 100%;
  overflow-x: hidden;
}

.search-card,
.data-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.search-card {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.table-wrapper {
  flex: 1;
  overflow: hidden; /* 重要：确保表格容器不溢出 */
}

.search-input {
  width: 300px;
}

.button-group {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.student-info {
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.student-info p {
  margin: 5px 0;
  color: #606266;
}

/* Element Plus 主题定制 */
:deep(.el-form-item__content),
:deep(.el-date-picker) {
  width: 100%;
}

:deep(.el-tag) {
  text-align: center;
  min-width: 60px;
}

:deep(.el-table) {
  --el-table-header-bg-color: #fff5f5;
}

:deep(.el-button--danger) {
  --el-button-bg-color: #c8161d;
  --el-button-border-color: #c8161d;
  --el-button-hover-bg-color: #e54b4b;
  --el-button-hover-border-color: #e54b4b;
  --el-button-active-bg-color: #c8161d;
  --el-button-active-border-color: #c8161d;
  --el-button-text-color: #fff;
}

:deep(.el-button--danger.is-plain) {
  --el-button-bg-color: #fff;
  --el-button-border-color: #c8161d;
  --el-button-text-color: #c8161d;
  --el-button-hover-text-color: #c8161d;
  --el-button-hover-bg-color: #fff5f5;
  --el-button-hover-border-color: #e54b4b;
  --el-button-active-bg-color: #fff5f5;
  --el-button-active-text-color: #c8161d;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #c8161d;
}
</style>
